import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:example/base/custom_widget.dart';
import 'package:example/config/color_config.dart';
import 'package:example/widget/my_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../utils/common.dart';


/// 搜索输入框
class SearchTextField extends CustomWidget<MySearchController> {
  final FocusNode? focusNode;
  final double? width;
  final double? height;
  final BorderRadius? borderRadius;
  final double? textSize;
  final Color? textColor;
  final FontWeight? fontWeight;
  final String? textHint;
  final double? textHintSize;
  final Color? textHintColor;
  final TextAlign textAlign;
  final Color? background;
  final int? maxLength;
  final int? maxLines;
  final BoxDecoration? shape;
  final TextInputType? keyboardType;
  final List<TextInputFormatter>? inputFormatters;
  final ValueChanged<String>? onChanged;
  final ValueChanged<String>? onSubmitted;
  final Function? onLeftClick;
  final EdgeInsets? closePadding;
  final GestureTapCallback? onCloseTap;
  final Color? closeColor;
  final double? closeHeight;
  final double? closeWidth;
  final String leftIconPath;
  final Color? leftIconColor;
  final double? leftIconHeight;
  final double? leftIconWidth;
  final double? leftIconMarginRight;
  final double? paddingLeft;
  final double? paddingRight;
  final String? counterText;
  final String? textContentText;
  final Color? counterColor;
  final EdgeInsets? padding;
  final bool obscureText;
  final TextInputAction? textInputAction;

  SearchTextField({
    Key? key,
    MySearchController? controller,
    bool isEnabled = true,
    bool showLeftIcon = true,
    bool showClose = true,
    this.obscureText = false,
    this.focusNode,
    this.height,
    this.width,
    this.borderRadius,
    this.textSize,
    this.textColor,
    this.fontWeight,
    this.textHint,
    this.textHintSize,
    this.textHintColor,
    this.textAlign = TextAlign.start,
    this.background = Colors.white,
    this.maxLines,
    this.maxLength,
    this.shape,
    this.keyboardType,
    this.inputFormatters,
    this.onChanged,
    this.onSubmitted,
    this.onLeftClick,
    this.closePadding,
    this.onCloseTap,
    this.closeColor,
    this.closeHeight,
    this.closeWidth,
    this.leftIconPath = "assets/svg/purchase_search.svg",
    this.leftIconColor,
    this.leftIconWidth,
    this.leftIconHeight,
    this.leftIconMarginRight,
    this.paddingLeft,
    this.paddingRight,
    this.counterText = "",
    this.counterColor,
    this.padding,
    this.textInputAction,
    this.textContentText,
  }) : super(
            MySearchController(
                isEnabled: isEnabled,
                showLeftIcon: showLeftIcon,
                showClose: showClose),
            key: key,
            externalController: controller) {
    if (controller != null) {
      controller.isEnabled = controller.isEnabled ?? isEnabled;
      controller.showLeftIcon = controller.showLeftIcon ?? showLeftIcon;
      controller.showClose = controller.showClose ?? showClose;
    }
  }

  @override
  Widget initView(BuildContext context, MySearchController controller) {
    String textContentEmpty = textContentText ?? '';
    if (textContentEmpty.isNotEmpty) {
      controller.setText(textContentText ?? '');
    }
    return Container(
      width: width,
      height: height ?? 40.w,
      padding: EdgeInsets.symmetric(horizontal: padding?.horizontal ?? 0),
      decoration: shape ??
          BoxDecoration(
            color: background,
            borderRadius: borderRadius ?? BorderRadius.circular(40.w),
          ),
      child: Row(
        // crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(width: paddingLeft ?? 19.w),
          Visibility(
            visible: controller.showLeftIcon == true,
            child: GestureDetector(
                child: Container(
                  color: Colors.transparent,
                  height: height ?? 40.w,
                  padding:
                      EdgeInsets.fromLTRB(0, 0, leftIconMarginRight ?? 8.w, 0),
                  child: MyImage(
                    path: leftIconPath,
                    width: leftIconWidth ?? 18.w,
                    height: leftIconHeight ?? 18.w,
                    color: leftIconColor,
                  ),
                ),
                onTap: () {
                  onLeftClick?.call();
                }),
          ),
          Expanded(
            child: TextField(
              textInputAction: textInputAction,
              textAlign: textAlign,
              enabled: controller.isEnabled,
              focusNode: focusNode,
              //加密显示时只能是1行
              maxLines: obscureText ? 1 : maxLines,
              controller: controller.inputController,
              enableSuggestions: false,
              keyboardType: keyboardType,
              inputFormatters: inputFormatters,
              maxLength: maxLength,
              obscureText: obscureText,
              style: TextStyle(
                color: textColor ?? ColorConfig.text,
                fontSize: textSize ?? 14.sp,
                fontWeight: fontWeight,
              ),
              decoration: InputDecoration(
                filled: true,
                isCollapsed: true,
                contentPadding:
                    EdgeInsets.symmetric(vertical: padding?.vertical ?? 0),
                fillColor: Colors.transparent,
                counterText: counterText,
                counterStyle:
                    TextStyle(color: counterColor ?? ColorConfig.text),
                hintText: textHint,
                hintStyle: TextStyle(
                  color: textHintColor ?? ColorConfig.text_gray,
                  fontSize: textHintSize ?? 14.sp,
                  fontWeight: fontWeight,
                ),
                border: InputBorder.none,
                focusedBorder: InputBorder.none,
              ),
              onChanged: (str) {
                controller.update([controller.idClose]);
                onChanged?.call(str);
              },
              onSubmitted: (str) {
                onSubmitted?.call(str);
              },
            ),
          ),
          SizedBox(width: paddingRight),
          _closeIcon(controller),
        ],
      ),
    );
  }

  /// 删除按钮
  _closeIcon(MySearchController controller) {
    return GetBuilder<MySearchController>(
      id: controller.idClose,
      init: controller,
      global: false,
      builder: (controller) {
        return Visibility(
          visible: isNotEmptyOrNull(controller.getText()) &&
              controller.isEnabled == true &&
              controller.showClose == true,
          child: GestureDetector(
            onTap: () {
              controller.setText("");
              onCloseTap?.call();
            },
            child: Container(
              height: double.infinity,
              padding: closePadding ?? EdgeInsets.fromLTRB(4.w, 0, 10.w, 0),
              child: MyImage(
                path: "assets/svg/ic_edit_clear.svg",
                width: closeWidth ?? 18.w,
                height: closeHeight ?? 18.w,
              ),
            ),
          ),
        );
      },
    );
  }
}

class MySearchController extends GetxController {
  final String idClose = "idClose";
  bool? isEnabled;
  bool? showLeftIcon;
  bool? showClose;
  TextEditingController inputController = TextEditingController();

  MySearchController({
    String text = "",
    this.isEnabled,
    this.showLeftIcon,
    this.showClose,
  }) {
    inputController.text = text;
  }

  String getText() => inputController.text;

  setText(String text) {
    inputController.text = text;
    update([idClose]);
  }

  setTextSelection(String text, {TextSelection? selection}) {
    inputController.text = text;
    inputController.selection = selection ??
        TextSelection.fromPosition(TextPosition(
            affinity: TextAffinity.downstream, offset: text.length));
    update([idClose]);
  }

  void setEnabled(bool isEnabled) {
    this.isEnabled = isEnabled;
    update();
  }
}
